<?php

class cntrlgroup implements viewController {
	private $area;
	private $side;
	private $dependencies = array("JavaScript" => array("facebox.js", "group.js"), "CSS" => array("facebox.css") );
	private $pageName = "Error";
	private $userObj;
	private $tools = "";
	
	private $groupName;
	private $groupID;
	private $instID;
	private $groupDescription;
	private $visibility;
	private $byInvitationOnly;
	
	private $userIsInGroup;
	
	public function __construct(user &$userObj){
		$this->userObj = $userObj;
		if($this->userObj->getAccessLevel() == -1 || $this->userObj->getAccessLevel() == ""){
			// User is not logged in
			header("Location: home");
		} else {
			parse_str( $_GET['act'] );
			$this->groupID = (int)$id;
			
			$groupInfo = group::getGroupInfo( $this->groupID );

			// Group doesnt exist. Direct them to an error page
			if($groupInfo == '') header('Location: error?e=3');

			$this->groupName = $groupInfo['name'];
			$this->groupDescription = $groupInfo['description'];
			$this->visibility = $groupInfo['private'];
			$this->byInvitation = $groupInfo['byInvitation'];
			$this->instID = $groupInfo['instID'];
			$this->instName = $groupInfo['instName'];
			
			$this->generateGroupPage();
		}
	}
	
	
	private function generateGroupPage(){
		if($this->checkAccessPermissions() == true){
			// The user is able to see this group, so generate the sidebar and the content.
			$this->generateSidebar();
			$this->generateContent();
		
		} else {
			// Check to see if the user is awaiting validation.
			$this->userValidating = (BOOL)$this->userObj->isInGroup( $this->groupID, 3 );
		
			if($this->visibility == 0){
				// Group is open. Display sidebar.
				$this->generateSidebar();
				$this->generatePreviewContent();
			} else {
				// The user should not be able to see this
				if($this->byInvitation == 0){
					$this->generateSidebar();
					$this->generatePreviewContent();
				} else{
					// If the group is private and invitation only, the user shouldnt be able to see this. Direct them to an error page.
					header("Location: error?e=12");
					exit;
				}
			}
		}
	}
	
	private function checkAccessPermissions(){
		// Is the user in the group?
		$this->userIsInGroup = (BOOL)$this->userObj->isInGroup( $this->groupID );
		if($this->userIsInGroup) return true;
		return false;
	}
		
	
	public function generateSidebar(){
		$this->side = new template("control.groupSidebar");
		
		$this->pageName = $this->groupName . "<var id=\"lang_219_groupResources\"></var>";
		
		$this->side->replaceAll( array("groupName" => $this->groupName, "groupDescription" => $this->groupDescription) );
		
		// Display additional information about the group to the user.
		$output = "<ul>";
		
		if((BOOL)$this->visibility){
			$output .= "<li><var id=\"lang_214_privGroup\"></var> </li>";
		} else {
			$output .= "<li><var id=\"lang_215_openGroup\"></var> </li>";
		}
		
		if((BOOL)$this->byInvitation){
			$output .= "<li><var id=\"lang_216_groupInvitation\"></var></li>";
		}
		
		$output .= "</ul>";
		
		if($this->instID != 1){
			$output .= "<var id=\"lang_217_groupNetworkPrefix\"></var> " . $this->instName . " <var id=\"lang_218_groupNetworkSuffix\"></var>";
		}
		
		if($this->userIsInGroup == 0){
			if((BOOL)$this->visibility && (BOOL)$this->byInvitation){
			
			} else {
				echo $this->userIsInGroup;
				if((BOOL)$this->visibility) {
					// Is the user validating?
					$output .= $this->userValidating ? "<br /><br /><button id='leave_group' disabled><var id=\"lang_211_reqMembership\"></var></button>" : "<br /><br /><button id='join_group'><var id=\"lang_211_reqMembership\"></var></button>";
				} else {
					$output .= "<button id='join_group'><var id=\"lang_213_joinGroup\"></var></button>";
				}
			}
		} else {
			$output .= "<br /><br /><button id='leave_group'><var id=\"lang_212_leaveGroup\"></var></button>";
		}
		
		$this->side->replace("extraContent", $output);
		
	}

	
	private function formatChartsAndReturn(template &$itemTemplate){
		$chartOutput = "";
		
		$images = chart::getGroupChartThumbs($this->groupID);
		
		foreach(chart::getGroupCharts($this->groupID) as $chart){
			$out = "<a href='chart?id=" . $chart['chID'] . "'>" . $chart['name'] . "</a>";
			$out .= "<p>" . $chart['description'] . "</p>";

			$imageURL = (array_key_exists($chart['chID'], $images)) ? $images[$chart['chID']] : SYS_BASEURL . "/images/document.png";
			
			// Is this IE & SVG?
			$browser = util::getBrowser();
			if(array_key_exists("msie", $browser) && strpos($imageURL, '.svg') !== FALSE ){
				$imageURL = preg_replace("/svg/i", 'wmf', $imageURL);
			} else {
				// If this is a SVG we need to change the template.
				if(strpos($imageURL, '.svg') !== FALSE){
					// We have a SVG
					
					// We need to strip off the http:// of the URL.
					$imageURL = preg_replace("/(http:\/\/)/i", "", $imageURL);
					$format = '<embed src="http://access.ecs.soton.ac.uk/seb/PicBoard/SVGProxy.php?r=%s" type="image/svg+xml" height="70" width="70">';
			
				} else {
					$format = "<img src='%s' height='70' width='70' />";
				}
				$imageTemplate = sprintf($format, $imageURL);			
			}
			

			$itemTemplate->replace("desc", $out);
			$itemTemplate->replace("image", $imageTemplate);
			$chartOutput .= $itemTemplate->get();
			$itemTemplate->reset();
		}	
		return $chartOutput;
		
	}
	
	private function formatBooksAndReturn(template &$itemTemplate){
		$bookOutput = "";
		
		$images = book::getGroupBookThumbs($this->groupID);
		
		$books = book::getGroupBooks($this->groupID);
				
		foreach($books as $book){
			$out = "<a href='book?id=" . $book['bID'] . "'>" . $book['name'] . "</a>";
			$out .= "<p>" . $book['description'] . "</p>";

			$imageURL = (array_key_exists($book['bID'], $images)) ? $images[$book['bID']] : SYS_BASEURL . "/images/document.png";

			// Is this IE & SVG?
			$browser = util::getBrowser();
			if(array_key_exists("msie", $browser) && strpos($imageURL, '.svg') !== FALSE ){
				$imageURL = preg_replace("/svg/i", 'wmf', $imageURL);
			} else {
				// If this is a SVG we need to change the template.
				if(strpos($imageURL, '.svg') !== FALSE){
					// We have a SVG
					
					// We need to strip off the http:// of the URL.
					$imageURL = preg_replace("/(http:\/\/)/i", "", $imageURL);
					$format = '<embed src="http://access.ecs.soton.ac.uk/seb/PicBoard/SVGProxy.php?r=%s" type="image/svg+xml" height="70" width="70">';
			
				} else {
					$format = "<img src='%s' height='70' width='70' />";
				}
				$imageTemplate = sprintf($format, $imageURL);			
			}
						
			$itemTemplate->replace("image", $imageTemplate);
			$itemTemplate->replace("desc", $out);
			$bookOutput .= $itemTemplate->get();
			$itemTemplate->reset();
		}	
		return $bookOutput;		
	}	
	
	private function formatUsersAndReturn(template &$userTemplate){
		$userOutput = "";
		
		$users = group::getUserList($this->userObj, $this->groupID);
				
		foreach($users as $user){

			$imageURL = ($user['isAdmin']) ? "user_business_32" : "user_blue_32";

						
			$userTemplate->replace("icon", $imageURL);
			$userTemplate->replace("firstName", $user['firstName']);
			$userTemplate->replace("lastName", $user['lastName']);
			$userOutput .= $userTemplate->get();
			$userTemplate->reset();
		}	
		return $userOutput;			
	}
	
	private function formatImagesAndReturn(template &$itemTemplate){
		$imagesOutput = "";
		
		foreach(images::getGroupLists($this->groupID) as $imageset){
			$out = "<a href='imageset?id=" . $imageset['isID'] . "'>" . $imageset['name'] . "</a>";

			$itemTemplate->replace("desc", $out);
			$itemTemplate->replace("image", "<img src=\"{absolute-url}/images/document.png\" height=\"70\" width=\"70\">");
			$imagesOutput .= $itemTemplate->get();
			$itemTemplate->reset();		
		}
		
		return $imagesOutput;
	}	
	
	private function generatePreviewContent(){
		$this->area = new template("area.groupPreview");
	}
	
	private function generateContent(){
		$dbCon = db::singleton();
	
		$this->area = new template("area.grouphome");

		$itemTemplate = new template("fragment.listDisplayItem");
		
		
		$chartOutput = $this->formatChartsAndReturn( $itemTemplate );
		$this->area->replace('chartList', $chartOutput);

		$bookOutput = $this->formatBooksAndReturn( $itemTemplate );
		$this->area->replace('bookList', $bookOutput);	
		
		$imagesOutput = $this->formatImagesAndReturn( $itemTemplate );
		$this->area->replace('imageList', $imagesOutput);
		
		$userOutput = $this->formatUsersAndReturn(new template('fragment.userListItem'));	
		$this->area->replace('userList', $userOutput);
		
		
		$rows = $dbCon->oneRow( "SELECT FOUND_ROWS()" );
		
		$this->area->replace('user-count', $rows['FOUND_ROWS()']);
		
	}
	
	private function generateAccessViolationPage(){
		
	}
	
	public function getSide(){
		return $this->side;
	}
	
	public function getArea(){
		return $this->area;
	}
	
	public function getDependencies(){
		return $this->dependencies;
	}

	public function getPageName(){
		return $this->pageName;
	}
	
	public function getTools(){
		return $this->tools;
	}	
}

?>